import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_scan_tool/bloc/device/device_bloc.dart';
import 'package:flutter_scan_tool/models/antenna.dart';
import 'package:flutter_scan_tool/models/app_theme.dart';
import 'package:flutter_scan_tool/page/edit_file_view.dart';
import 'package:flutter_scan_tool/utils/mutable.dart';

class DeviceSetting extends StatefulWidget {
  final List<AntennaData> antennaList;
  const DeviceSetting({Key? key, required this.antennaList}) : super(key: key);

  @override
  State<DeviceSetting> createState() => _DeviceSettingState();
}

class _DeviceSettingState extends State<DeviceSetting> {
  final ScrollController scrollController = ScrollController();

  List<AntennaData> antennaList = [];

  @override
  void initState() {
    super.initState();
    setState(() {
      antennaList = widget.antennaList;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.appTheme.containerBackgroundColor(),
      body: Stack(
        children: [
          AnimatedList(
              padding: const EdgeInsets.only(top: 50, bottom: 16),
              controller: scrollController,
              initialItemCount: antennaList.length,
              itemBuilder: (context, index, animation) {
                return antennaView(context, antennaList[index], animation);
              }),
          Container(
            width: double.infinity,
            alignment: Alignment.topRight,
            margin: const EdgeInsets.only(right: 16, top: 16),
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).pop();
              },
              child: const Icon(
                Icons.close,
                size: 40.0,
              ),
            ),
          ),
          Container(
            width: MediaQuery.of(context).size.width,
            alignment: Alignment.topCenter,
            child: Padding(
              padding: const EdgeInsets.only(top: 20),
              child: Text(
                '设备设置',
                style: AppTheme.appTheme
                    .headline2(fontWeight: FontWeight.bold, fontSize: 18),
              ),
            ),
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          DeviceBloc bloc= context.read<DeviceBloc>();
          bloc.add(DeviceConfigUpdateEvent(antenaData: antennaList));
          Navigator.of(context).pop();
        },
        child: const Text('保存'),
      ),
    );
  }

  Widget antennaView(
      BuildContext context, AntennaData antenna, Animation<double> animation) {
    return SizeTransition(
      sizeFactor:
          CurvedAnimation(parent: animation, curve: Curves.fastOutSlowIn),
      child: Container(
        margin: const EdgeInsets.only(top: 20, left: 10, right: 10),
        decoration: BoxDecoration(
            shape: BoxShape.rectangle,
            borderRadius: const BorderRadius.all(Radius.circular(15)),
            color: AppTheme.appTheme.cardBackgroundColor(),
            boxShadow: AppTheme.appTheme.containerBoxShadow()),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
                margin: const EdgeInsets.only(top: 16),
                child: Row(
                  children: <Widget>[
                    const Padding(
                      padding: EdgeInsets.only(left: 10, right: 10),
                      child: Text("端口号"),
                    ),
                    const SizedBox(
                      width: 5,
                    ),
                    Text(
                      antenna.antennaNo.toString(),
                      style: AppTheme.appTheme.numHeadline1(
                          fontWeight: FontWeight.w400, fontSize: 16),
                    ),
                  ],
                )),
            Row(
              children: <Widget>[
                const Padding(
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Text("高点"),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      editNote(context, antenna.powerValue.toString(), (value) {
                        setState(() {
                          if (value != "") {
                            antenna.powerValue = int.parse(value);
                          } else {
                            antenna.powerValue = 0;
                          }
                        });
                      }, TextInputType.number);
                    },
                    child: Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.only(
                          left: 16, right: 16, top: 10, bottom: 10),
                      decoration: BoxDecoration(
                          shape: BoxShape.rectangle,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(8)),
                          color: AppTheme.appTheme.containerBackgroundColor()),
                      alignment: Alignment.topLeft,
                      width: double.infinity,
                      constraints: const BoxConstraints(minHeight: 40),
                      child: Text(
                        '${antenna.powerValue <= 0 ? '填写数字' : antenna.powerValue}',
                        style: antenna.powerValue == 0
                            ? AppTheme.appTheme.headline2(
                                fontSize: 16, fontWeight: FontWeight.w500)
                            : AppTheme.appTheme.headline1(
                                fontSize: 16, fontWeight: FontWeight.w500),
                      ),
                    ),
                  ),
                ),
              ],
            ),
            // Row(
            //   children: <Widget>[
            //     const Padding(
            //       padding: EdgeInsets.only(left: 10, right: 10),
            //       child: Text("低点"),
            //     ),
            //     Expanded(
            //       child: GestureDetector(
            //         onTap: () {
            //           editNote(context, antenna.lowRate.toString(), (value) {
            //             setState(() {
            //               if (value != "") {
            //                 antenna.lowRate = int.parse(value);
            //               } else {
            //                 antenna.lowRate = 0;
            //               }
            //             });
            //           }, TextInputType.number);
            //         },
            //         child: Container(
            //           padding: const EdgeInsets.all(8),
            //           margin: const EdgeInsets.only(
            //               left: 16, right: 16, top: 10, bottom: 10),
            //           decoration: BoxDecoration(
            //               shape: BoxShape.rectangle,
            //               borderRadius:
            //                   const BorderRadius.all(Radius.circular(8)),
            //               color: AppTheme.appTheme.containerBackgroundColor()),
            //           alignment: Alignment.topLeft,
            //           width: double.infinity,
            //           constraints: const BoxConstraints(minHeight: 40),
            //           child: Text(
            //             '${antenna.lowRate <= 0 ? '填写数字' : antenna.lowRate}',
            //             style: antenna.lowRate == 0
            //                 ? AppTheme.appTheme.headline2(
            //                     fontSize: 16, fontWeight: FontWeight.w500)
            //                 : AppTheme.appTheme.headline1(
            //                     fontSize: 16, fontWeight: FontWeight.w500),
            //           ),
            //         ),
            //       ),
            //     ),
            //   ],
            // ),
          ],
        ),
      ),
    );
  }

  void editNote(BuildContext context, String value,
      ValueChanged<String> valueChange, TextInputType inputType) async {
    Mutable<String> content = Mutable(value);
    await Navigator.of(context).push(
      PageRouteBuilder(
          opaque: false,
          pageBuilder: (context, ani1, ani2) {
            return EditFiledView(
              content: content,
              key: GlobalKey(),
              onValueChange: valueChange,
              inputType: inputType,
            );
          },
          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            Animation<double> myAnimation = Tween<double>(begin: 0, end: 1.0)
                .animate(CurvedAnimation(
                    parent: animation,
                    curve: Curves.easeOutSine,
                    reverseCurve:
                        const Interval(0, 0.5, curve: Curves.easeInSine)));
            return Transform(
              transform: Matrix4.translationValues(
                  0, 100 * (1 - myAnimation.value), 0),
              child: FadeTransition(
                opacity: myAnimation,
                child: child,
              ),
            );
          }),
    );
  }
}
